﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace DemoStock.Common
{
    public class Num2StringConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is float f)
            {
                string strNum = f.ToString();
                if (string.IsNullOrWhiteSpace(strNum))
                {
                    return "0.00";
                }
                int idx = strNum.IndexOf('.');
                if (idx < 0)
                {
                    return string.Format("{0}.00", strNum);
                }
                else
                {
                    int ilength = strNum.Length - 1 - idx;
                    if (ilength < 2)
                    {
                        return strNum.PadRight(strNum.Length + 2 - ilength, '0');
                    }
                    else
                    {
                        return Math.Round(f, 2).ToString();
                    }
                }
            }
            return "0.00";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class Num2StringConvertWithChar : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is float f)
            {
                string strPrefix = "";
                if (f > 0)
                {
                    strPrefix = "+";
                }
                string strNum = f.ToString();
                if (string.IsNullOrWhiteSpace(strNum))
                {
                    return "0.00";
                }
                int idx = strNum.IndexOf('.');
                if (idx < 0)
                {
                    return strPrefix + string.Format("{0}.00", strNum);
                }
                else
                {
                    int ilength = strNum.Length - 1 - idx;
                    if (ilength < 2)
                    {
                        return strPrefix + strNum.PadRight(strNum.Length + 2 - ilength, '0');
                    }
                    else
                    {
                        return strPrefix + Math.Round(f, 2).ToString();
                    }
                }
            }
            return "0.00";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}
